using System;
using System.Collections.Generic;
using Servlets.Api;
using System.Linq;

namespace Servlets.Http
{
	public class QueryString : IValue<string>
	{
		private Dictionary<string, List<string>> map = new Dictionary<string, List<string>>();
		
		public string this [string key] {
			get {
				if(!map.ContainsKey(key)) {
					return null;
				}
				return map[key][0];
			}
		}
		
		public string[] All(string key) {
			if(!map.ContainsKey(key)) {
				return null;
			}
			return map[key].ToArray();
		}
		
		public QueryString() { }
		
		public QueryString(string queryString)
		{
			ParseQueryString(queryString);
		}
		
		private void ParseQueryString(string s) {
			string[] split = s.Split('&');
			foreach(string keyvalue in split) {
				string[] kvSplit = keyvalue.Split('=');
				string key = Uri.UnescapeDataString(kvSplit[0].Replace('+', ' '));
				string val = Uri.UnescapeDataString(kvSplit[1].Replace('+', ' '));
				GetNewOrStored(key).Add(val);
			}
		}
		
		private List<string> GetNewOrStored(string key) {
			if(!map.ContainsKey(key)) {
				map[key] = new List<string>();
			}
			return map[key];
		}
		
	}
}

